package band.wukong.practice.javase.core.io.stream.serializable;

import java.io.*;
import java.util.Date;

/**
 * Desc:
 * Author: sunjs
 * Date: 2009-11-20 13:55:18
 */
public class AboutSerializable {
    //    private static final String OBJ_FILE = "E:\\workspace\\TestJava\\src\\com\\jsun\\javase\\io\\doc\\objFile.obj";
    private static final String OBJ_FILE = "E:\\somecode\\TestJava\\src\\com\\jsun\\javase\\io\\doc\\objFile.obj";

    public static void main(String[] args) throws Exception {
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(OBJ_FILE));

        String obj1 = "hello";
        Date obj2 = new Date();
        Boy obj3 = new Boy("Cadeo", 21);

        //序列化对象
        out.writeObject(obj1);
        out.writeObject(obj2);
        out.writeObject(obj3);
        out.close();

        //反序列化对象
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(OBJ_FILE));
        String obj11 = (String) in.readObject();
        System.out.println("obj11 : " + obj11);
        System.out.println("obj11==obj1 : " + (obj11 == obj1));
        System.out.println("obj11.equals(obj1) : " + obj11.equals(obj1));

        Date obj22 = (Date) in.readObject();
        System.out.println("obj22 : " + obj22);
        System.out.println("obj22==obj2 : " + (obj22 == obj2));
        System.out.println("obj22.equals(obj2) : " + obj22.equals(obj2));

        Boy obj33 = (Boy) in.readObject();
        System.out.println("obj33 : " + obj33);
        System.out.println("obj33==obj3 : " + (obj33 == obj3));
        System.out.println("obj33.equals(obj3) : " + obj33.equals(obj3));

    }

    /*
        对象序列化的步骤：
        1.  创建一个对象输出流，它可以包装一个其他类型的输出流。
            ObjectOutputStream out =  new ObjectOutputStream(
                new FileOutputStream(FILE_OUT)
            );
        2.  通过对相输出流的writeObject()方法写对象
            out.writeObject("hello");
            out.writeObject(new Date());
     */

    /*
        对象反序列化的步骤：
        1.  创建一个对象输入流，他可以包装一个其他类型的输入流。
            ObjectInputStream in = new ObjectInputStream(
                new FileInputStream(FILE_IN)
            );
        2.  通过对象输入流的readObject()方法读取对象
            String obj1 = (String)out.readObject();
            Date obj2 = (Date)out.readObject();
     */

    private static class Boy implements Serializable {
        private String name;
        private int age;

        private Boy(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String toString() {
            return "Boy{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}
